package com.wx.app.ui;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.widget.RadioGroup;

import com.example.administrator.newemptyapplication.R;
import com.wx.app.dao.DaoHelper;
import com.wx.app.mylib.app.BaseActivity;
import com.wx.app.ui.fragment.ChannelFragment;
import com.wx.app.ui.fragment.HomeFragment;
import com.wx.app.ui.fragment.MineFragment;
import com.wx.app.ui.fragment.MsgContainerFragment;

import java.util.ArrayList;

public class MainActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {

    private RadioGroup mRg;
    private ArrayList<Fragment> mFragmentList;
    private MsgContainerFragment mMessageContainerFrg;
    private MineFragment mineFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        DaoHelper.getInstance().getNoteDao();
        initData();
        initView();
    }

    private void initData() {
        mFragmentList = new ArrayList<>();
        HomeFragment homeFragment = new HomeFragment();
        mMessageContainerFrg = new MsgContainerFragment();
        ChannelFragment infoFragment = new ChannelFragment();
        mineFragment = new MineFragment();
        mFragmentList.add(homeFragment);
        mFragmentList.add(mMessageContainerFrg);
        mFragmentList.add(infoFragment);
        mFragmentList.add(mineFragment);
        getSupportFragmentManager().beginTransaction().add(R.id.container, mFragmentList.get(0)).commitAllowingStateLoss();
    }

    private void initView() {
        mRg = (RadioGroup) findViewById(R.id.main_radio);
        assert mRg != null;
        mRg.setOnCheckedChangeListener(this);


    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.rb_home:
                replaceFragment(0);
                break;
            case R.id.rb_msg:
                replaceFragment(1);
                break;
            case R.id.rb_information:
                replaceFragment(2);
                break;
            case R.id.rb_mine:
                replaceFragment(3);
                break;
        }
    }

    private int mPosition = 0;

    private void replaceFragment(int i) {
        if (i != mPosition) {
            Fragment fragment = mFragmentList.get(i);
            getSupportFragmentManager().beginTransaction().hide(mFragmentList.get(mPosition));
            if (fragment.isAdded()) {
                getSupportFragmentManager().beginTransaction().show(fragment).commitAllowingStateLoss();
                fragment.onResume();
            } else {
                getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).commitAllowingStateLoss();
            }
        }
        mPosition = i;
    }



}
